package com.newlink.building.common_base.utils

import android.content.Context
import org.json.JSONObject
import java.io.IOException

/**
 * 配置文件读取帮助类
 * 从项目的配置文件中读取各种配置参数
 */
object Base_ConfigHelper {

    /**
     * 阿里云 EMAS 配置
     */
    data class EmasConfig(
        val appKey: String,
        val appSecret: String,
        val packageName: String
    )

    /**
     * Google Services 配置
     */
    data class GoogleServicesConfig(
        val projectNumber: String,
        val projectId: String,
        val mobilesdkAppId: String,
        val apiKey: String
    )

    /**
     * 从 aliyun-emas-services.json 读取阿里云配置
     */
    fun getEmasConfig(context: Context): EmasConfig? {
        return try {
            val jsonString = readRawResourceFile(context, "aliyun-emas-services")
                ?: readAssetFile(context, "aliyun-emas-services.json")

            val jsonObject = JSONObject(jsonString)
            val config = jsonObject.getJSONObject("config")

            EmasConfig(
                appKey = config.getString("emas.appKey"),
                appSecret = config.getString("emas.appSecret"),
                packageName = config.getString("emas.packageName")
            )
        } catch (e: Exception) {
            NLog.e("[ConfigHelper] Failed to read EMAS config: ${e.message}")
            // 返回默认配置作为兜底
            getDefaultEmasConfig()
        }
    }

    /**
     * 从 google-services.json 读取 Google Services 配置
     */
    fun getGoogleServicesConfig(context: Context): GoogleServicesConfig? {
        return try {
            val jsonString = readRawResourceFile(context, "google_services")
                ?: readAssetFile(context, "google-services.json")

            val jsonObject = JSONObject(jsonString)
            val projectInfo = jsonObject.getJSONObject("project_info")
            val client = jsonObject.getJSONArray("client").getJSONObject(0)
            val clientInfo = client.getJSONObject("client_info")
            val apiKey = client.getJSONArray("api_key").getJSONObject(0)

            GoogleServicesConfig(
                projectNumber = projectInfo.getString("project_number"),
                projectId = projectInfo.getString("project_id"),
                mobilesdkAppId = clientInfo.getString("mobilesdk_app_id"),
                apiKey = apiKey.getString("current_key")
            )
        } catch (e: Exception) {
            NLog.e("[ConfigHelper] Failed to read Google Services config: ${e.message}")
            // 返回默认配置作为兜底
            getDefaultGoogleServicesConfig()
        }
    }

    /**
     * 从 raw 资源读取文件内容
     */
    private fun readRawResourceFile(context: Context, resourceName: String): String? {
        return try {
            val resourceId = context.resources.getIdentifier(resourceName, "raw", context.packageName)
            if (resourceId != 0) {
                context.resources.openRawResource(resourceId).bufferedReader().use { it.readText() }
            } else {
                null
            }
        } catch (e: Exception) {
            NLog.e("[ConfigHelper] Failed to read raw resource: $resourceName - ${e.message}")
            null
        }
    }

    /**
     * 从 assets 读取文件内容
     */
    private fun readAssetFile(context: Context, fileName: String): String {
        return try {
            context.assets.open(fileName).bufferedReader().use { it.readText() }
        } catch (e: IOException) {
            throw IOException("Failed to read asset file: $fileName", e)
        }
    }

    /**
     * 获取默认的 EMAS 配置（兜底方案）
     */
    private fun getDefaultEmasConfig(): EmasConfig {
        return EmasConfig(
            appKey = "335591731",
            appSecret = "ef7d67f9ddec4fd18110f57e82c8944a",
            packageName = "com.newlink.building"
        )
    }

    /**
     * 获取默认的 Google Services 配置（兜底方案）
     */
    private fun getDefaultGoogleServicesConfig(): GoogleServicesConfig {
        return GoogleServicesConfig(
            projectNumber = "686561309518",
            projectId = "newlink-c9945",
            mobilesdkAppId = "1:686561309518:android:5ac7fdea4a78cf0ab2a41f",
            apiKey = "AIzaSyAIb54nWmWqG7eETL9JrqYDT4aQOtEYJdg"
        )
    }

    /**
     * 获取配置诊断信息
     */
    fun getConfigDiagnosticInfo(context: Context): String {
        val emasConfig = getEmasConfig(context)
        val googleConfig = getGoogleServicesConfig(context)

        return """
            Configuration Diagnostic Info:
            - EMAS Config: ${if (emasConfig != null) "✓ Available (AppKey: ${emasConfig.appKey})" else "✗ Not Found"}
            - Google Services Config: ${if (googleConfig != null) "✓ Available (Project: ${googleConfig.projectId})" else "✗ Not Found"}
        """.trimIndent()
    }

    /**
     * 验证配置文件是否存在且有效
     */
    fun validateConfigs(context: Context): Boolean {
        val emasValid = getEmasConfig(context) != null
        val googleValid = getGoogleServicesConfig(context) != null

        NLog.e("[ConfigHelper] Config validation - EMAS: $emasValid, Google: $googleValid")

        return emasValid && googleValid
    }
}